package mobile.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import controllers.TaskCenter;
import mobile.config.AppConfig;
import play.Play;
import play.cache.Cache;

public class JPushUtil {

	public static final Logger log = LoggerFactory.getLogger(JPushUtil.class);

	public static void push(Long taskId) {
		PushPayload payload = buildPushObject_all_all_alert();
		if(payload!=null)	{
			return;
		}
		ClientConfig  cfg = ClientConfig.getInstance();
		cfg.setApnsProduction(true);
		JPushClient jpushClient = new JPushClient(AppConfig.JPUSH_MASTER_SECRET, AppConfig.JPUSH_APP_KEY, null, cfg);
		try {
			PushResult result = jpushClient.sendPush(payload);
			log.info("Got result - " + result);

		} catch (APIConnectionException e) {
			// Connection error, should retry later
			log.error("Connection error, should retry later", e);

		} catch (APIRequestException e) {
			// Should review the error, and fix the request
			log.error("Should review the error, and fix the request", e);
			log.info("HTTP Status: " + e.getStatus());
			log.info("Error Code: " + e.getErrorCode());
			log.info("Error Message: " + e.getErrorMessage());
		}
	}

	public static PushPayload buildPushObject_all_all_alert() {
		String unlimit = Play.configuration.getProperty("unlimit");
		if("yes".equals(unlimit)){
			return PushPayload.alertAll("有新的任务发布了,快去处理吧");
		}
		Calendar c = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String cDateStr = sdf.format(new Date());
		int hour = c.get(Calendar.HOUR_OF_DAY);
		if(hour<=8){
			String date = (String) Cache.get("push_one");
			if(cDateStr.equals(date)){
				return null;
			}
			Cache.set("push_one", cDateStr, "1d");
		}else if(8<hour&&hour<=16){
			String date = (String) Cache.get("push_two");
			if(cDateStr.equals(date)){
				return null;
			}
			Cache.set("push_two", cDateStr, "1d");
		}else if(16<hour&&hour<=23){
			String date = (String) Cache.get("push_three");
			if(cDateStr.equals(date)){
				return null;
			}
			Cache.set("push_three", cDateStr, "1d");
		}
		return PushPayload.alertAll("有新的任务发布了,快去处理吧");
	}
	
	
}
